<template>
  <div class="open-source-container">
    <!-- 顶部搜索和操作区域 -->
    <el-card class="search-card" :body-style="{ padding: '20px' }">
      <div class="card-header">
        <div class="left-section">
          <h2 class="section-title">开源项目管理</h2>
          <span class="subtitle">管理您的开源项目展示</span>
        </div>
        <div class="right-section">
          <el-button type="primary" :icon="Plus" @click="handleAddProject" class="add-button">添加项目</el-button>
        </div>
      </div>
      <el-form :inline="true" class="search-form">
        <el-form-item label="项目名称:">
          <el-input v-model="searchForm.name" placeholder="请输入项目名称" clearable />
        </el-form-item>
        <el-form-item label="技术栈:">
          <el-select v-model="searchForm.technology" placeholder="选择技术栈" clearable>
            <el-option v-for="item in technologyOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 项目列表展示区域 -->
    <div class="projects-container">
      <el-empty v-if="projectList.length === 0" description="暂无开源项目" />
      <transition-group name="project-list" tag="div" class="project-grid">
        <el-card 
          v-for="(project, index) in projectList" 
          :key="project.id" 
          class="project-card"
          :body-style="{ padding: '0' }"
          shadow="hover"
        >
          <div class="project-image-container">
            <el-image 
              :src="project.img_Url" 
              fit="cover"
              class="project-image"
              loading="lazy"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>加载失败</span>
                </div>
              </template>
            </el-image>
            <div class="project-overlay">
              <el-button-group class="action-buttons">
                <el-button type="primary" :icon="Edit" circle @click.stop="handleEdit(project)" />
                <el-button type="danger" :icon="Delete" circle @click.stop="handleDelete(project)" />
                <el-button type="success" :icon="Link" circle @click.stop="openLink(project.git_Url)" />
              </el-button-group>
            </div>
          </div>
          <div class="project-content">
            <h3 class="project-title">{{ project.name }}</h3>
            <div class="project-tech-stack">
              <el-tag 
                v-for="(tech, techIndex) in project.technology_Stack" 
                :key="techIndex"
                :type="tagTypes[techIndex % tagTypes.length]"
                effect="light"
                size="small"
                class="tech-tag"
              >
                {{ tech }}
              </el-tag>
            </div>
            <p class="project-description">{{ project.description }}</p>
            <div class="project-footer">
              <span class="project-date">
                <el-icon><Calendar /></el-icon>
                {{ formatDate(project.update_time || project.create_time) }}
              </span>
              <el-tag 
                :type="project.status === 1 ? 'success' : 'info'" 
                size="small"
              >
                {{ project.status === 1 ? '已发布' : '草稿' }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </transition-group>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[8, 12, 24, 36]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>

    <!-- 添加/编辑项目对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑项目' : '添加项目'"
      width="60%"
      destroy-on-close
    >
      <el-form
        ref="projectFormRef"
        :model="projectForm"
        :rules="projectRules"
        label-width="100px"
        class="project-form"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="projectForm.name" placeholder="请输入项目名称" />
        </el-form-item>
        
        <el-form-item label="项目图片">
          <div v-if="!projectForm.img_Url" class="upload-container">
            <el-upload
              class="project-uploader"
              action="https://back.xuxiao888.com/upload"
              name="image"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
            >
              <el-icon class="uploader-icon"><Plus /></el-icon>
              <div class="upload-text">点击上传项目图片</div>
            </el-upload>
          </div>
          <div v-else class="preview-container">
            <el-image :src="projectForm.img_Url" class="preview-image" />
            <div class="preview-actions">
              <el-button type="primary" size="small" @click="projectForm.img_Url = ''">更换图片</el-button>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="Git 地址" prop="git_Url">
          <el-input v-model="projectForm.git_Url" placeholder="请输入项目Git地址" />
        </el-form-item>
        
        <el-form-item label="技术栈" prop="technology_Stack">
          <el-select
            v-model="projectForm.technology_Stack"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或添加技术栈"
            style="width: 100%"
          >
            <el-option
              v-for="item in technologyOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="项目描述" prop="description">
          <el-input
            v-model="projectForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入项目描述"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-switch
            v-model="projectForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="发布"
            inactive-text="草稿"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { Plus, Edit, Delete, Link, Picture, Calendar } from '@element-plus/icons-vue'
import { GetAllOpenSource } from '@/api/source' // 假设这是获取开源项目的API

// 定义项目类型
interface Project {
  id: string
  name: string
  git_Url: string
  img_Url: string
  technology_Stack: string[]
  description: string
  create_time: string
  update_time: string
  status: number
}

// 搜索表单
const searchForm = reactive({
  name: '',
  technology: ''
})

// 技术栈选项
const technologyOptions = ref([
  'Vue', 'React', 'Angular', 'TypeScript', 'JavaScript',
  'Node.js', 'Express', 'Koa', 'NestJS', 'Spring Boot',
  'Python', 'Django', 'Flask', 'Go', 'Rust',
  'MongoDB', 'MySQL', 'PostgreSQL', 'Redis', 'Docker'
])

// 标签类型
const tagTypes = ['', 'success', 'warning', 'danger', 'info']

// 项目列表数据
const projectList = ref<Project[]>([])
const filteredProjects = ref<Project[]>([])
const loading = ref(true)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(8)

// 对话框控制
const dialogVisible = ref(false)
const isEdit = ref(false)
const projectFormRef = ref<FormInstance>()

// 项目表单
const projectForm = reactive<Project>({
  id: '',
  name: '',
  git_Url: '',
  img_Url: '',
  technology_Stack: [],
  description: '',
  create_time: '',
  update_time: '',
  status: 1
})

// 表单验证规则
const projectRules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  git_Url: [
    { required: true, message: '请输入Git地址', trigger: 'blur' },
    { pattern: /^(https?:\/\/|git@)/, message: '请输入有效的Git地址', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入项目描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  technology_Stack: [
    { required: true, message: '请至少选择一个技术栈', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一个技术栈', trigger: 'change' }
  ]
}

// 获取项目列表
const fetchProjects = async () => {
  loading.value = true
  try {
    const response = await GetAllOpenSource()
    projectList.value = response.data || []
    total.value = projectList.value.length
    applyFilters()
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

// 应用筛选条件
const applyFilters = () => {
  filteredProjects.value = projectList.value.filter(project => {
    const nameMatch = !searchForm.name || project.name.toLowerCase().includes(searchForm.name.toLowerCase())
    const techMatch = !searchForm.technology || project.technology_Stack.includes(searchForm.technology)
    return nameMatch && techMatch
  })
  total.value = filteredProjects.value.length
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  applyFilters()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.technology = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 添加项目
const handleAddProject = () => {
  isEdit.value = false
  Object.assign(projectForm, {
    id: '',
    name: '',
    git_Url: '',
    img_Url: '',
    technology_Stack: [],
    description: '',
    create_time: '',
    update_time: '',
    status: 1
  })
  dialogVisible.value = true
}

// 编辑项目
const handleEdit = (project: Project) => {
  isEdit.value = true
  Object.assign(projectForm, JSON.parse(JSON.stringify(project)))
  dialogVisible.value = true
}

// 删除项目
const handleDelete = (project: Project) => {
  ElMessageBox.confirm(
    `确定要删除项目 "${project.name}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 这里应该调用删除API
    // 模拟删除成功
    projectList.value = projectList.value.filter(item => item.id !== project.id)
    applyFilters()
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

// 打开链接
const openLink = (url: string) => {
  window.open(url, '_blank')
}

// 上传前验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response: any) => {
  if (response && response.url) {
    projectForm.img_Url = response.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!projectFormRef.value) return
  
  await projectFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 这里应该调用保存API
        // 模拟保存成功
        if (isEdit.value) {
          // 更新项目
          const index = projectList.value.findIndex(item => item.id === projectForm.id)
          if (index !== -1) {
            projectList.value[index] = { ...projectForm }
          }
          ElMessage.success('更新成功')
        } else {
          // 添加项目
          const newProject = { 
            ...projectForm,
            id: `project_${Date.now()}`,
            create_time: new Date().toISOString(),
            update_time: new Date().toISOString()
          }
          projectList.value.unshift(newProject)
          ElMessage.success('添加成功')
        }
        applyFilters()
        dialogVisible.value = false
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    } else {
      return false
    }
  })
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 生命周期钩子
onMounted(() => {
  fetchProjects()
})
</script>

<style scoped lang="scss">
.open-source-container {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .left-section {
        .section-title {
          margin: 0;
          font-size: 22px;
          font-weight: 600;
          color: #303133;
        }
        
        .subtitle {
          font-size: 14px;
          color: #909399;
          margin-top: 4px;
          display: block;
        }
      }
      
      .add-button {
        padding: 10px 20px;
        font-weight: 500;
      }
    }
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }
  
  .projects-container {
    min-height: 400px;
  }
  
  .project-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
  }
  
  .project-card {
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
    height: 100%;
    display: flex;
    flex-direction: column;
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
      
      .project-overlay {
        opacity: 1;
      }
    }
    
    .project-image-container {
      position: relative;
      height: 180px;
      overflow: hidden;
      
      .project-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.5s ease;
      }
      
      .image-error {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 100%;
        background-color: #f5f7fa;
        color: #909399;
        
        .el-icon {
          font-size: 32px;
          margin-bottom: 8px;
        }
      }
      
      .project-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        opacity: 0;
        transition: opacity 0.3s ease;
        
        .action-buttons {
          display: flex;
          gap: 10px;
        }
      }
    }
    
    .project-content {
      padding: 16px;
      flex: 1;
      display: flex;
      flex-direction: column;
      
      .project-title {
        margin: 0 0 12px;
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        line-height: 1.4;
      }
      
      .project-tech-stack {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
        margin-bottom: 12px;
        
        .tech-tag {
          border-radius: 4px;
          transition: all 0.2s ease;
          
          &:hover {
            transform: scale(1.05);
          }
        }
      }
      
      .project-description {
        margin: 0 0 16px;
        font-size: 14px;
        color: #606266;
        line-height: 1.6;
        flex: 1;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 3;
        overflow: hidden;
      }
      
      .project-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 13px;
        color: #909399;
        
        .project-date {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  
  // 表单样式
  .project-form {
    max-width: 100%;
    
    .upload-container, .preview-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .project-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        width: 300px;
        height: 180px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        transition: border-color 0.3s;
        
        &:hover {
          border-color: #409EFF;
        }
        
        .uploader-icon {
          font-size: 28px;
          color: #8c939d;
          margin-bottom: 8px;
        }
        
        .upload-text {
          color: #8c939d;
          font-size: 14px;
        }
      }
      
      .preview-image {
        width: 300px;
        height: 180px;
        object-fit: cover;
        border-radius: 6px;
      }
      
      .preview-actions {
        margin-top: 10px;
      }
    }
  }
  
  // 动画效果
  .project-list-enter-active,
  .project-list-leave-active {
    transition: all 0.5s ease;
  }
  
  .project-list-enter-from,
  .project-list-leave-to {
    opacity: 0;
    transform: translateY(30px);
  }
  
  .project-list-move {
    transition: transform 0.5s ease;
  }
}
</style>